package com.xzbd.test.composit;

import java.util.Vector;

import org.eclipse.swt.events.DisposeEvent;
import org.eclipse.swt.events.DisposeListener;
import org.eclipse.swt.events.MouseAdapter;
import org.eclipse.swt.events.MouseEvent;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Label;

public class PictureLabel extends Composite {

	Label image, text;
	Color white;
	Vector<ImageClickedListener> imageClickedListeners = new Vector<>();

	PictureLabel(Composite parent, int style) {
		super(parent, style);
		white = new Color(null, 255, 255, 255);
		image = new Label(this, 0);
		text = new Label(this, 0);
		setBackground(white);
		text.setBackground(white);
		image.setBackground(white);
		addDisposeListener(new DisposeListener() {
			public void widgetDisposed(DisposeEvent e) {
				PictureLabel.this.widgetDisposed(e);
			}
		});
		image.addMouseListener(new MouseAdapter() {
			public void mouseDown(MouseEvent event) {
				if (event.button == 1) {
					PictureLabel.this.mouseDown(event);
				}
			}
		});
		text.addMouseListener(new MouseAdapter() {
			public void mouseDown(MouseEvent event) {
				if (event.button == 1) {
					PictureLabel.this.mouseDown(event);
				}
			}
		});
		addMouseListener(new MouseAdapter() {
			public void mouseDown(MouseEvent event) {
				if (event.button == 1) {
					PictureLabel.this.mouseDown(event);
				}
			}
		});

		setLayout(new PictureLabelLayout());

	}

	void widgetDisposed(DisposeEvent e) {
		white.dispose();
	}

	public void mouseDown(MouseEvent event) {
		ImageClickedEvent e = new ImageClickedEvent(this, event.x, event.y);
		int size = imageClickedListeners.size();
		for (int i = 0; i < size; i++) {
			ImageClickedListener listener = (ImageClickedListener) imageClickedListeners.elementAt(i);
			listener.imageClicked(e);
		}
	}

	public void addImageClickedListener(ImageClickedListener listener) {
		imageClickedListeners.addElement(listener);
	}

	public void removeImageClickedListener(ImageClickedListener listener) {
		imageClickedListeners.removeElement(listener);
	}

	public Image getImage() {
		return image.getImage();
	}

	public void setImage(Image image) {
		this.image.setImage(image);
		layout(true);
	}

	public String getText() {
		return text.getText();
	}

	public void setText(String text) {
		this.text.setText(text);
		layout(true);
	}

}
